package com.unf.edu.rms.controller.userlogin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.unf.edu.rms.controller.validation.UserLoginValidator;
import com.unf.edu.rms.dao.Student;
import com.unf.edu.rms.dao.UserLogin;
import com.unf.edu.rms.service.UserLoginService;
import com.unf.edu.rms.service.UsersService;
import com.unf.edu.rms.util.Password;
import com.unf.edu.rms.util.RMSConstants;

@Controller
public class UserLoginController 
{

	@Autowired
	private UserLoginService userLoginService;
	@Autowired
	private UsersService usersService;
	@Autowired
	HttpServletRequest request;
	
		
	@RequestMapping("/UserLogin")
	public String viewLogin(@ModelAttribute("userLogin") UserLogin userLogin,BindingResult bindingResult,Model model) {
		System.out.println("UserLoginController.viewLogin()==============");
		this.clearSession();
		return RMSConstants.USER_LOGIN_VIEW;
	}
	
	@RequestMapping("/Dashboard")
	public String viewDashboard() {
		
		System.out.println("UserLoginController.viewDashboard()==============");
		return RMSConstants.DASHBOARD_VIEW;
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@ModelAttribute("userLogin") UserLogin userLogin,BindingResult bindingResult,Model model) throws Exception {
		System.out.println("UserLoginController.addUser()======username and password===="+userLogin.getUserName()+":"+userLogin.getPassword());
		boolean validUser = false;
		String userName = userLogin.getUserName();
		String password = userLogin.getPassword();
		UserLoginValidator userLoginValidator = new UserLoginValidator();
		userLoginValidator.validate(userLogin, bindingResult);
		
		System.out.println("UserLoginController.login()============bindingResult.getErrorCount()"+bindingResult.getErrorCount());;
		//userLoginValidator.validate(arg0, arg1)
		if(!bindingResult.hasErrors())
		{
			validUser = userLoginService.validateUser(userName,password);
			userLogin = userLoginService.getUserLogin(userName);
			model.addAttribute("userLogin", userLogin);
			if(validUser)
			{	
				HttpSession session = request.getSession();
				session.setAttribute("loggedInUser", true);
				session.setAttribute("loginId", userLoginService.getUserFacultyId(userName));
				session.setAttribute("roleId", userLoginService.getUserRole(userName));
				session.setAttribute("userId", userLoginService.getUserLoginId(userName));
				
				if(userLoginService.getFirstTimeLogin(userName)){
					System.out.println("UserLoginId " + userLogin.getUserLoginId());
					return firstTimeLogin(userLogin, userLogin.getUserLoginId(), model);
				}
				
				return RMSConstants.DASHBOARD_VIEW;
				
			}
			else
			{
				bindingResult.rejectValue("password", "wrong.username.or.password");
				return RMSConstants.USER_LOGIN_VIEW;
			}
		}
		else
		{
			return RMSConstants.USER_LOGIN_VIEW;
		}
		
	}
	
	@RequestMapping(value = "/firstTimeLogin", method = RequestMethod.POST)
	public String firstTimeLogin(@ModelAttribute("userLogin") UserLogin userLogin, @RequestParam(required=true) int userLoginId,Model model) {
		
		userLogin = userLoginService.getUserLoginById(userLoginId);
		model.addAttribute("userLogin", userLogin);
		System.out.println("UserName: " + userLogin.getUserName() + "  UserLoginId: " + userLoginId);
		return RMSConstants.FIRST_TIME_LOGIN;
	}
	
	@RequestMapping(value = "/changeProfile")
	public String changeProfile(Model model) {
		HttpSession session = request.getSession();
		int userLoginId = Integer.parseInt(session.getAttribute("userId").toString());
		
		UserLogin userLogin = userLoginService.getUserLoginById(userLoginId);
		model.addAttribute("userLogin", userLogin);
		System.out.println("UserName: " + userLogin.getUserName() + "  UserLoginId: " + userLoginId);
		return RMSConstants.FIRST_TIME_LOGIN;
	}
	
	
	@RequestMapping(value = "/saveChanges", method = RequestMethod.POST)
	public String saveChanges(@ModelAttribute("userLogin") UserLogin userLogin, BindingResult bindingResult, Model model) throws Exception{
		System.out.println("UserName: " + userLogin.getUserName() + "   UserLoginId: " + userLogin.getUserLoginId() + "  Pw: " + userLogin.getPassword() + "  SQ: " + userLogin.getSecurityQuestion() + "  SA: " + userLogin.getSecurityAnswer());
		
			Password pw = new Password();
			String password = pw.encryptPassword(userLogin.getPassword());
			
			UserLogin userUpdate = userLoginService.getUserLoginById(userLogin.getUserLoginId());
			userUpdate.setPassword(password);
			userUpdate.setSecurityQuestion(userLogin.getSecurityQuestion());
			userUpdate.setSecurityAnswer(userLogin.getSecurityAnswer());
			userUpdate.setFirstTimeLogin("N");
			usersService.updateUser(userUpdate);
			return RMSConstants.DASHBOARD_VIEW;
		
	}
	
	@RequestMapping(value="/ForgotPassword")
	public String forgotPassword(Model model){
		UserLogin userLogin = new UserLogin();
		model.addAttribute("userLogin", userLogin);
		return RMSConstants.FORGOT_PASSWORD;
	}
	
	@RequestMapping(value="/SecurityCheckOne", method = RequestMethod.POST)
	public String securityCheckOne(@ModelAttribute("userLogin") UserLogin userLogin, BindingResult bindingResult, Model model){
		
		System.out.println("Requested Username: " + userLogin.getUserName());
		String userName = userLogin.getUserName();
		boolean foundUser = false;
		
		if(userName == null || userName.equals("")){
			bindingResult.rejectValue("userLogin.userName", "error.userName.noneSpecified");
		}
		else {
			List<UserLogin> userList = usersService.viewUserTable();
			
			for(UserLogin user:userList){
				
				if(user.getUserName().equals(userName)){
					foundUser = true;
					userLogin = user;
				}
			}
		}
		if(!foundUser){
			bindingResult.reject("userLogin.userName", "error.userName.invalid");
		}
		if(!bindingResult.hasErrors()){
			userLogin.setSecurityAnswer("");
			model.addAttribute("userLogin", userLogin);
			return RMSConstants.SECURITY_VIEW;
		}
		else {
			return RMSConstants.FORGOT_PASSWORD;
		}
	}
	
	@RequestMapping(value = "/SecurityCheckTwo")
	public String securityCheckTwo(@ModelAttribute("userLogin") UserLogin userLogin, BindingResult bindingResult, Model model){
		
		System.out.println("Given Security Answer:  " + userLogin.getSecurityAnswer());
		UserLogin user = usersService.getUserById(userLogin.getUserLoginId());
		
		if(user.getSecurityAnswer().equals(userLogin.getSecurityAnswer())){
			System.out.println("Success");
			
		}
		else{
			bindingResult.reject("userLogin.securityAnswer", "error.userName.wrongAnswer");
			System.out.println("Failure");
		}
		
		if(!bindingResult.hasErrors()){
			return firstTimeLogin(userLogin, userLogin.getUserLoginId(), model);
		}
		else{
			return RMSConstants.SECURITY_VIEW;
		}
		
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public String logout(@ModelAttribute("userLogin") UserLogin userLogin,BindingResult bindingResult,Model model) {
			this.clearSession();
			return RMSConstants.USER_LOGIN_VIEW;
	}
	
	private void clearSession()
	{
		HttpSession session = request.getSession();
		//session.setAttribute("loggedInUser", false);
		session.invalidate();
		//request.getSession().setAttribute("roleId",0);
	}
	
	public int checkValidateSession(){
		HttpSession session = request.getSession();
		int roleId = 0;
		if(session.getAttribute("roleId") == null){
			
		}
		if(session.getAttribute("roleId") != null){
			roleId = Integer.parseInt(session.getAttribute("roleId").toString());
			if(roleId==0){
				this.clearSession();
			}
		}
		return roleId;
	}
	
	public int getSessionUserId(){
		HttpSession session = request.getSession();
		
		int userLoginId = Integer.parseInt(session.getAttribute("userId").toString());
		
		return userLoginId;
	
	}
	
}
